package com.diyizu.dao.impl;

import com.diyizu.dao.IStudentInfoDao;
import com.diyizu.domain.Student;

import java.io.*;
import java.util.ArrayList;

public class StudentInfoDaoImpl implements IStudentInfoDao {

    @Override
    public void addStudent(Student stu)  {
        ArrayList<Student> addStu = new ArrayList<>();
        addStu.add(stu);
        if (findAllStudents()!=null){
            ArrayList<Student> allStudents = findAllStudents();
            for (Student student : allStudents) {
                addStu.add(student);
            }
        }
        writer(addStu);
    }

    private void writer(ArrayList<Student> addStu) {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("information_system\\student.txt"));
            oos.writeObject(addStu);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteStudent(String sid) {
        ArrayList<Student> alllist = findAllStudents();
        int index = getIndex(sid);
            alllist.remove(index);
            writer(alllist);
    }

    @Override
    public void updateStudent(String sid, Student stu) {
        ArrayList<Student> alllist = findAllStudents();
        int index = getIndex(sid);
        alllist.set(index, stu);
        writer(alllist);

    }

    @Override
    public ArrayList<Student> findAllStudents() {
        ObjectInputStream ois = null;
        ArrayList<Student> allStudent = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("information_system\\student.txt"));
            allStudent = (ArrayList<Student>) ois.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return allStudent;
    }

    @Override
    public int getIndex(String sid) {
        ArrayList<Student> alllist = findAllStudents();
        for (int i = 0; i < alllist.size(); i++) {
            Student student = alllist.get(i);
            if (student.getSid().equals(sid)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public Student getSid(String phone) {
        ArrayList<Student> array = findAllStudents();
        for (int i = 0; i < array.size(); i++) {
            Student student = array.get(i);
            if (student.getPhone().equals(phone)){
                return student;
            }
        }
        return null;
    }
    @Override
    public Student getId(String name) {
        ArrayList<Student> array = findAllStudents();
        for (int i = 0; i < array.size(); i++) {
            Student student = array.get(i);
            if (student.getName().equals(name)){
                return student;
            }
        }
        return null;
    }
}
